package com.jxin.mall.config.plan;

import com.jxin.mall.core.util.ProtoStuffUtil;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import javax.validation.constraints.NotNull;

/**
 *  Protobuf 的redis序列化器实现
 * @author 蔡佳新
 * @version 1.0
 * @since jdk 1.8
 */
public class ProtobufRedisSerializer<T> implements RedisSerializer<T> {
    private final Class <T> type;

    /**
     * Creates a new {@link ProtobufRedisSerializer} for the given target {@link Class}.
     * @param type 类型
     * @author 蔡佳新
     */
    public ProtobufRedisSerializer(Class<T> type) {
        this.type = type;
    }

    @Override
    public T deserialize(@NotNull byte[] byteArr) throws SerializationException {
        try {
            return (T) byteArr;
        } catch (Exception ex) {
            throw new SerializationException(ex.getMessage(), ex);
        }
    }

    @Override
    public byte[] serialize(@NotNull Object obj) throws SerializationException {
        try {
            return ProtoStuffUtil.serialize(obj);
        } catch (Exception ex) {
            throw new SerializationException(ex.getMessage(), ex);
        }
    }

    private Class<T> getType() {
        return type;
    }
}
